const db = wx.cloud.database()
let isGood = false
var util = require("../../../util/util.js")
Page({
  data: {
    list: [],
    show: false,
    message: "",
    messageList: [],
    display: "none",
    allDisplay: "none",
    placeholder: "留下你的精彩评论吧...",
    autoFocus: false,
    searchValue: '',
  },
  onChangeSearch(e) {
    this.setData({
      searchValue: e.detail,
    });
  },
  onClickSearch() {
    var that = this;
    wx.showLoading({
      title: '搜索中...',
    })
    that.setData({
      allDisplay: "none"
    })
    db.collection('say').where({
      show: true,
      flag: that.data.title,
      information: db.RegExp({
        regexp: that.data.searchValue,
        options: 'i',
      })
    }).get({
      success: res => {
        if (res.data.length == 0) {
          wx.showToast({
            icon: "none",
            title: '暂无此内容',
          })
        }
        that.setData({
          list: res.data
        })
        that.setLove()
        setTimeout(function () {
          wx.stopPullDownRefresh() //停止下拉刷新
          wx.hideLoading({
            success: (res) => {},
          })
          that.setData({
            allDisplay: ""
          })
        }, 1000);
      }
    })
  },
  //发送留言
  sendMessage(e) {
    const that = this;
    if (that.data.message == "") {
      wx.showModal({
        content: '请输入留言内容...',
        showCancel: false,
        title: '提示'
      })
    } else {
      wx.showLoading({
        title: '检测内容中...',
      })
      wx.cloud.callFunction({
        name: 'add',
        data: {
          content: that.data.message
        }
      }).then(res => {
        if (res.result.errcode == 0) {
          //内容合法
          if (that.data.placeholder.substring(0, 1) == "@") {
            var replayInfo = []
            replayInfo = [{
              img: that.data.avatarUrl,
              name: that.data.nickName,
              data: that.data.message,
              replayWho: that.data.replayWho,
              time: util.formatTime(new Date()),
              openid: that.data.myOpenid
            }]
            wx.cloud.callFunction({
              name: 'replay',
              data: {
                _id: that.data.replayId,
                replayInfo: replayInfo
              },
              success: function (res) {
                that.getMessage(that.data.id)
                wx.hideLoading({
                  success: (res) => {},
                })
                wx.showToast({
                  icon: "none",
                  title: '回复成功',
                })
              },
              fail: console.error
            })
          } else {
            db.collection('message').add({
              data: {
                id: that.data.id,
                message: that.data.message,
                avatarUrl: that.data.avatarUrl,
                nickName: that.data.nickName,
                time: util.formatTime(new Date())
              },
              success: function (res) {
                that.setData({
                  message: "",
                  dataMessageSum: that.data.dataMessageSum + 1
                })
                that.getMessage(that.data.id)
                wx.hideLoading({
                  success: (res) => {},
                })
                wx.showToast({
                  icon: "none",
                  title: '发表成功'
                })
              }
            })
          }
          var index = that.data.curindex
          var item = that.data.list
          var num = item[index].commentNum

          var messageSum = that.data.messageSum

          item[index].commentNum = (num + 1)

          that.setData({
            list: item,
            messageSum: (messageSum + 1)
          })
          //增加评论数
          wx.cloud.callFunction({
            name: 'message',
            data: {
              _id: that.data.id
            },
            success: function (res) {

            },
            fail: console.error
          })
          //订阅消息
          wx.cloud.callFunction({
            name: 'response',
            data: {
              openid: that.data.duifangOpenid,
              flag: that.data.title,
              title: that.data.wenzhangbiaoti.substring(0, 10),
              huifuren: that.data.nickName,
              huifuleirong: that.data.message.substring(0, 10),
              time: util.formatTime(new Date())
            }
          }).then(res => {
            console.log(res)
          })
          that.setData({
            message: "",
            placeholder: "留下你的精彩评论吧..."
          })
        } else {
          wx.hideLoading({
            success: (res) => {},
          })
          wx.showModal({
            content: '对不起，您的内容已违规！',
            showCancel: false,
            title: '提示',
          })
        }
      }).catch(err => {

      })
    }

  },
  //点击回复时候
  replay(e) {
    var that = this;
    wx.requestSubscribeMessage({
      tmplIds: ['AadcW-r08ZUw7Wl3oZsplWCs9oXLhJAlf25tC-4wuxo'], // 此处可填写多个模板 ID，但低版本微信不兼容只能授权一个
      success(res) {

      }
    })
    this.setData({
      replayId: e.currentTarget.dataset.id,
      placeholder: "@" + e.currentTarget.dataset.name + "：",
      replayWho: e.currentTarget.dataset.name,
      autoFocus: true,
      myOpenid: wx.getStorageSync('openid'),
      duifangOpenid: e.currentTarget.dataset.openid,
    })

  },
  //回复，回复中的人
  replayReplay(e) {
    var that = this;
    this.setData({
      replayId: e.currentTarget.dataset.id,
      placeholder: "@" + e.currentTarget.dataset.name + "：",
      replayWho: e.currentTarget.dataset.name,
      myOpenid: wx.getStorageSync('openid'),
      duifangOpenid: e.currentTarget.dataset.openid,
    })
  },
  // 输入框值的改变
  onChange(event) {
    this.setData({
      message: event.detail
    })
    console.log(event.detail);
  },
  //弹框
  showPopup(e) {
    var that = this;
    wx.requestSubscribeMessage({
      tmplIds: ['AadcW-r08ZUw7Wl3oZsplWCs9oXLhJAlf25tC-4wuxo'], // 此处可填写多个模板 ID，但低版本微信不兼容只能授权一个
      success(res) {

      }
    })
    wx.showLoading({
      title: '加载中...',
    })
    console.log()
    that.setData({
      show: true,
      id: e.currentTarget.dataset.id,
      curindex: e.currentTarget.dataset.curindex,
      messageSum: e.currentTarget.dataset.commentnum,
      wenzhangbiaoti: e.currentTarget.dataset.wenzhangbiaoti,
      duifangOpenid: e.currentTarget.dataset.openid
    });

    that.getMessageCount()
    that.getMessage(e.currentTarget.dataset.id)


  },
  //获取留言数据
  getMessage(e) {
    var that = this;
    db.collection('message').orderBy('time', 'desc').where({
      id: e
    }).limit(8).get({
      success: function (res) {
        that.setData({
          messageList: res.data,
        })
      }
    })
    setTimeout(function () {
      wx.hideLoading({
        success: (res) => {},
      })
      that.setData({
        display: ""
      })
    }, 1500);
  },
  //去框
  onClose() {
    this.setData({
      show: false,
      messageList: [],
      display: "none",
      id: ""
    });
  },
  onLoad: function (e) {
    var that = this;
    wx.showLoading({
      title: '加载中...',
    })
    that.setData({
      title: e.title
    })
    that.getList()
    that.getCount()
    that.getUser()
  },
  //设置哪些被点赞了
  setLove() {
    var that = this;
    db.collection('sayGood').where({
      _openid: wx.getStorageSync('openid')
    }).get({
      success: function (res) {
        var yuanList = that.data.list
        var goodList = res.data
        for (var yuan in yuanList) {
          for (var index in goodList) {
            if (yuanList[yuan]._id == goodList[index].id) {
              yuanList[yuan].isGood = true;
            }
          }
        }
        that.setData({
          list: yuanList,
        })
      }
    })
  },
  //获取用户数据
  getUser() {
    var that = this;
    wx.getUserInfo({
      success: function (res) {
        that.setData({
          avatarUrl: res.userInfo.avatarUrl,
          nickName: res.userInfo.nickName,
        })
      }
    })
    setTimeout(function () {
      wx.hideLoading({
        success: (res) => {},
      })
      that.setData({
        allDisplay: ""
      })
    }, 1500);
  },
  //获取条数
  getCount() {
    var that = this;
    db.collection("say").where({
      flag: that.data.title
    }).count({
      success: function (res) {
        console.log(res.total)
        that.setData({
          dataSum: res.total
        })
      }
    })
  },
  //获取留言条数
  getMessageCount() {
    var that = this;
    db.collection("message").where({
      id: that.data.id
    }).count({
      success: function (res) {
        console.log(res.total)
        that.setData({
          dataMessageSum: res.total
        })
      }
    })
  },
  //获取6条数据
  getList() {
    var that = this
    db.collection('say').limit(6).orderBy('time', 'desc').where({
      flag: that.data.title,
      show: true
    }).get({
      success: function (res) {
        that.setData({
          list: res.data,
        })
      },
      fail: function (event) {}
    })
    that.setLove() //设置哪些被点赞了

  },
  //留言下拉加载
  loadMore() {
    var that = this;
    var temp1 = [];
    if (that.data.messageList.length < that.data.dataMessageSum) {
      try {
        wx.showLoading({
          title: '加载中...',
        })
        db.collection('message').skip(that.data.messageList.length).limit(8).orderBy('time', 'desc').where({
          id: that.data.id
        }).get({

          success: function (res) {

            if (res.data.length > 0) {
              for (var i = 0; i < res.data.length; i++) {
                var tempshopping1 = res.data[i];
                temp1.push(tempshopping1);
              }
              var dataMessage = {};
              dataMessage = that.data.messageList.concat(temp1);
              that.setData({
                messageList: dataMessage,
              })
            }
            wx.hideLoading();
          },
          fail: function (event) {
            console.log("======" + event);
          }
        })
      } catch (e) {
        console.error(e);
      }
    } else if (that.data.messageList.length >= that.data.dataMessageSum) {
      wx.showToast({
        title: '已为你加载全部',
        icon: 'none'
      })
    }
  },
  /* 
   * 页面上拉触底事件的处理函数图片
   * 
   */
  onReachBottom: function () {
    var that = this;
    var temp = [];
    if (that.data.list.length < that.data.dataSum) {
      try {
        wx.showLoading({
          title: '加载中...',
        })
        db.collection('say').skip(that.data.list.length).limit(6).orderBy('time', 'desc').where({
          flag: that.data.title,
          show: true
        }).get({

          success: function (res) {

            if (res.data.length > 0) {
              for (var i = 0; i < res.data.length; i++) {
                var tempshopping = res.data[i];
                temp.push(tempshopping);
              }
              var dataList = {};
              dataList = that.data.list.concat(temp);
              that.setData({
                list: dataList,
              })
            }
            wx.hideLoading();
          },
          fail: function (event) {
            console.log("======" + event);
          }
        })
      } catch (e) {
        console.error(e);
      }
    } else if (that.data.list.length >= that.data.dataSum) {
      wx.showToast({
        title: '已为你加载全部',
        icon: 'none'
      })
    }
  },
  onPullDownRefresh: function () {
    var that = this;
    that.setData({
      allDisplay: "none"
    })
    that.getList()
    setTimeout(function () {
      wx.stopPullDownRefresh() //停止下拉刷新

      that.setData({
        allDisplay: ""
      })
    }, 1500);
  },
  goAdd() {
    wx.navigateTo({
      url: 'add/add?flag=' + this.data.title,
    })
  },
  good(e) {
    var that = this;
    var index = e.currentTarget.dataset.curindex
    var item = that.data.list
    var num = item[index].goodNum

    isGood = item[index].isGood

    console.log(num)
    if (isGood) {
      item[index].goodNum = (num - 1)
      item[index].isGood = false
      that.setData({
        list: item
      })
      //删除点赞数据
      db.collection('sayGood').where({
        id: e.currentTarget.dataset.id
      }).get({
        success: function (res) {
          db.collection('sayGood').doc(res.data[0]._id).remove({
            success: function (ress) {
              //删除成功
            }
          })
        }
      })
    } else {
      item[index].goodNum = (num + 1)
      item[index].isGood = true
      that.setData({
        list: item
      })
      //增加数据
      db.collection('sayGood').add({
        data: {
          id: e.currentTarget.dataset.id
        },
        success: function (res) {

        }
      })
    }
    wx.cloud.callFunction({
      name: 'good',
      data: {
        isGood: item[index].isGood,
        _id: e.currentTarget.dataset.id
      },
      success: function (res) {

      },
      fail: console.error
    })
  },
  lookImage(e) {
    console.log(e)
    var that = this;
    var src = e.target.dataset.url; //获取data-src
    var imgList = [e.target.dataset.url]; //获取data-list
    //图片预览
    wx.previewImage({
      current: src, // 当前显示图片的http链接
      urls: imgList // 需要预览的图片http链接列表
    })
  }
})